package com.authine.cloudpivot.ext.controller.person;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.config.EducationEnum;
import com.authine.cloudpivot.web.api.config.FirstEducationEnum;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.authine.cloudpivot.ext.Utils.DocAPI;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 人员信息记录 基础表
 **/
@RestController

@RequestMapping("/public/personBaseInfo")
@Slf4j
public class PersonInfoRecordController extends BaseController {


    @Autowired
    CloudSqlService sqlService;


    @GetMapping("delPerson")
    public ResponseResult delPerson(String bizId) {

        DocAPI api = new DocAPI();
        String token = api.getToken();
        String HRParentAttribute = "";
        String EmpStatus = "";
        String PersonCode = "";
        Map<String, Object> objectMap = null;

        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("personInfoRecord", bizId);

        List<Map<String, Object>> subSheet = (List<Map<String, Object>>) bizObject.getObject("personInfoRecordDetail");


        int n = subSheet.size();
        for (int i = 0; i < n; i++) {
            objectMap = subSheet.get(i);
            EmpStatus = (String) objectMap.get("status");// 获取狀態
            if (!EmpStatus.equals("出列")) {
                continue;
            }
            PersonCode = (String) objectMap.get("personNumber");// 获取狀態
            HRParentAttribute = "HR " + PersonCode;
            System.out.println(HRParentAttribute);
            //加对应框架
            JSONObject FolderIdObj = api.getFileID(HRParentAttribute);//
            int FolderNum = Integer.parseInt(FolderIdObj.getString("num"));
            if (FolderNum == 0) {
                continue;
            }
            JSONArray FolderIdDataArray = FolderIdObj.getJSONArray("data");
            JSONObject FolderIdObj0 = FolderIdDataArray.getJSONObject(0);
            String folederid = FolderIdObj0.getString("id");
            api.getRemove(token, folederid);
        }

        return getOkResponseResult("成功");
    }

    /**
     * 人员信息记录 基础表  审批流完成后 数据写到-人员信息记录 基础表 基础
     */
    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.personInfoRecord, bizId);

        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("personInfoRecordDetail");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = "";

        for (Map<String, Object> map : list) {

            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.personInfoBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                String companyNumber = (String) map.get("companyNumber");
                String personNumber = (String) map.get("personNumber");

                log.info("基础表-人员信息基础操作失败 companyNumber={},personNumber={}", companyNumber, personNumber);
                log.info(e.getMessage(), e);
            }

        }
    }

    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.toVoidPersonInfoRecord, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("voidPersonInfoRecordDetail");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {


            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.personInfoBase, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作废操作成功 ");
                //调用存储过程
                callProcessToVoid(id);

            } catch (Exception e) {
                String companyNumber = (String) map.get("companyNumber");
                String personNumber = (String) map.get("personNumber");
                log.info("基础表-人员信息基础作废操作失败 personNumber={},companyNumber={}", personNumber, companyNumber);
                log.info(e.getMessage(), e);
            }

        }
    }

    /**
     * 调用存储过程
     * ------人员信息  基础信息
     * exec    SyncEmpBaseInfo
     * OrgID		nvarchar(100),			----公司代码
     * FirstHROrg int,				----0  空白   1 √
     * EmpCode	nvarchar(100),			----人员代码
     * Name       nvarchar(100),			----名称
     * Sex		nvarchar(10),			----男 male  女 female
     * EmpStatus nvarchar(10),			---- 0   √    1  x
     * BirthD y	nvarchar(50),			----YYYY-MM-DD
     * FirstEducation    nvarchar(20),		----第一学历   'Senior'  '高中及以下'   'JuniorCollege'  '大专'   'Bachelor1'  '本1'  'Bachelor2'  '本2'   'Bachelor3' '本3'
     * Education		   nvarchar(50),	----学历  'Senior'  '高中及以下'  'JuniorCollege'  '大专'  'Bachelor1'  '本1'   'Bachelor2' '本2'   'Bachelor3'  '本3'   'Master' '硕士研究生'  'Master1'  '硕1'  'Master2'   '硕2' 'Doctor0'  '博士研究生'  'Doctor' '博士'
     * Nationality nvarchar(100),    ----国籍
     * NativePlace	   nvarchar(500),	----籍贯
     * Nation			   nvarchar(50),	----民族
     * BirthAddress	   nvarchar(500),	----出生地
     * Marriage		   nvarchar(50),	----婚姻状况
     * Party			   nvarchar(50),	----政治面貌
     * Auditor		   nvarchar(50)		----审批人   02.0100 李**
     *
     * @param bizId
     */
    private void callProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.personInfoBase);
        StringBuilder sql = new StringBuilder("SELECT company,firstDept,personNumber,personName,sex,status,birth,firstEducation,education,nationality,nativePlace,nation,birthplace,maritalStatus,politicCountenance,auditer from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程
        String company = MapUtils.getString(map, "company", "");
        String firstDeptTemp = MapUtils.getString(map, "firstDept", "");
        Integer firstDept = "√".equals(firstDeptTemp) ? 1 : 0;

        String personNumber = MapUtils.getString(map, "personNumber", "");
        String personName = MapUtils.getString(map, "personName", "");
        String sex = MapUtils.getString(map, "sex", "");
        sex = "M".equals(sex) ? "male" : "female";
        String status = MapUtils.getString(map, "status", "");
        status = "√".equals(status) ? "0" : "1";
//        Date birthTemp = (Date) map.get("birth");
//        String birth = birthTemp == null ? null : DateFormatUtils.format(birthTemp, "yyyy-MM-dd");

        LocalDateTime birthTemp = (LocalDateTime) map.get("birth");
        String birth =  ObjectUtils.isEmpty(birthTemp) ? "" : birthTemp.toLocalDate().toString();



        String firstEducation = MapUtils.getString(map, "firstEducation", "");
        Optional<FirstEducationEnum> firstEducationEnum = FirstEducationEnum.valueOfText(firstEducation);
        firstEducation = firstEducationEnum.isPresent() ? firstEducationEnum.get().name() : null;
        String education = MapUtils.getString(map, "education", "");
//        Optional<EducationEnum> educationEnum = EducationEnum.valueOfText(education);
//        education = educationEnum.isPresent() ? educationEnum.get().name() : null;
        String nationality = MapUtils.getString(map, "nationality", "");
        String nativePlace = MapUtils.getString(map, "nativePlace", "");
        String nation = MapUtils.getString(map, "nation", "");
        String birthplace = MapUtils.getString(map, "birthplace", "");
        String maritalStatus = MapUtils.getString(map, "maritalStatus", "");
        maritalStatus =

                "√".equals(maritalStatus) ? "1" : "0";
        String politicCountenance = MapUtils.getString(map, "politicCountenance", "");
        String auditer = MapUtils.getString(map, "auditer", "");

//        Assert.isFalse(StringUtils.isEmpty(company), "{}不能为空", "company");
////        Assert.isFalse(firstDept==null ,"{}不能为空","firstDept");
//        Assert.isFalse(StringUtils.isEmpty(personNumber), "{}不能为空", "personNumber");
//        Assert.isFalse(StringUtils.isEmpty(personName), "{}不能为空", "personName");
//        Assert.isFalse(StringUtils.isEmpty(sex), "{}不能为空", "sex");
//        Assert.isFalse(StringUtils.isEmpty(status), "{}不能为空", "status");
//        Assert.isFalse(StringUtils.isEmpty(birth), "{}不能为空", "birth");
//        Assert.isFalse(StringUtils.isEmpty(firstEducation), "{}不能为空", "firstEducation");
//        Assert.isFalse(StringUtils.isEmpty(education), "{}不能为空", "education");
//        Assert.isFalse(StringUtils.isEmpty(nationality), "{}不能为空", "nativePlace");
////        Assert.isFalse(StringUtils.isEmpty(nativePlace),"{}不能为空","nativePlace");
//        Assert.isFalse(StringUtils.isEmpty(nation), "{}不能为空", "nation");
////        Assert.isFalse(StringUtils.isEmpty(birthplace),"{}不能为空","birthplace");
//        Assert.isFalse(StringUtils.isEmpty(maritalStatus), "{}不能为空", "maritalStatus");
//        Assert.isFalse(StringUtils.isEmpty(politicCountenance), "{}不能为空", "politicCountenance");
//        Assert.isFalse(StringUtils.isEmpty(auditer), "{}不能为空", "auditer");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncEmpBaseInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                company, firstDept, personNumber, personName, sex, status, birth, firstEducation, education, nationality, nativePlace, nation, birthplace, maritalStatus, politicCountenance, auditer);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============personName人员姓名：{}", personName);
        log.info("\n=============存储过程执行完成");

    }

    /**
     * 调用作废存储过程
     * --------人员信息记录   基础信息 作废
     * exec    EmpBaseVoid
     * CompanyFID nvarchar(100),   ----公司FID
     * EmpCode nvarchar(100)   ----人员代码
     *
     * @param bizId
     */
    private void callProcessToVoid(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.personInfoBase);
        StringBuilder sql = new StringBuilder("SELECT company,personNumber from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程

        String company = MapUtils.getString(map, "company", "");
        String personNumber = MapUtils.getString(map, "personNumber", "");

        Assert.isFalse(StringUtils.isEmpty(company), "{}不能为空", "company");
        Assert.isFalse(StringUtils.isEmpty(personNumber), "{}不能为空", "personNumber");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].EmpBaseVoid '%s','%s'",
                company, personNumber);

        log.info("\n==========准备调用作废存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============作废存储过程执行完成");

    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity7";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);

        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.personInfoBase);
        String companyNumber = (String) data.get("companyNumber");
        String personNumber = (String) data.get("personNumber");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where companyNumber='").append(companyNumber).append("' and personNumber='")
                .append(personNumber).append("';");


        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 转换成  基础表-总公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();


        //出生日期
        data.put("birth", map.get("birth"));
        //出生地
        data.put("birthplace", map.get("birthplace"));
        //公司
        data.put("company", map.get("company"));
        //公司代码
        data.put("companyNumber", map.get("companyNumber"));
        //学历
        data.put("education", map.get("education"));
        //第一人事组织
        data.put("firstDept", map.get("firstDept"));
        //第一学历
        data.put("firstEducation", map.get("firstEducation"));
        //婚姻状况
        data.put("maritalStatus", map.get("maritalStatus"));
        //民族
        data.put("nation", map.get("nation"));
        //国籍
        data.put("nationality", map.get("nationality"));
        //籍贯
        data.put("nativePlace", map.get("nativePlace"));
        //姓名
        data.put("personName", map.get("personName"));
        //人员代码
        data.put("personNumber", map.get("personNumber"));
        //政治面貌
        data.put("politicCountenance", map.get("politicCountenance"));
        //性别
        data.put("sex", map.get("sex"));
        //状态
        data.put("status", map.get("status"));

        //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("auditer", auditer);

        return data;
    }
}
